package com.wswy.wzcx.jpush;


import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.util.Log;
import java.util.LinkedList;
import java.util.concurrent.atomic.AtomicBoolean;

public abstract class SimplePushOperator implements IPushOperator{

  private static final String TAG = "SimplePushOperator";

  private static final int MSG_NEXT = 30;

  private Handler msgHandler;

  private LinkedList<Object> msgList =new LinkedList<>();

  private AtomicBoolean isProcessing = new AtomicBoolean(false);

  public SimplePushOperator(){

    msgHandler = new Handler(new Callback() {
      @Override
      public boolean handleMessage(Message msg) {
        if(msg.what == MSG_NEXT && !msgList.isEmpty()){

          innerHandle(msgList.pollFirst());
          return true;
        }
        return false;
      }
    });

  }

  private void innerHandle(Object bean){
    isProcessing.set(true);
    onProcessOperator(bean);
  }


  protected void onProcessOperator(Object bean){
    Log.e(TAG, "onProcessOperator --> "+bean);
  }

  protected final void next(){
    isProcessing.set(false);
    Log.e(TAG, "next --> ");
    msgHandler.removeMessages(MSG_NEXT);
    msgHandler.sendEmptyMessageDelayed(MSG_NEXT,8000);
  }

  protected void addOperator(Object bean){
//    if(!msgList.isEmpty()){
//      msgList.remove(Integer.valueOf(type));
//    }

    msgList.add(bean);

    if(!isProcessing.get()){
      msgHandler.removeMessages(MSG_NEXT);
      msgHandler.sendEmptyMessageDelayed(MSG_NEXT,8000);
    }

    Log.e(TAG, "addOperator --> "+bean);
  }

}
